/**
 * Created by nico on 2015/12/25.
 */
var async = require('async');
var AV = require('leanengine');

var activityService = require('../models/activityService')
var ActivityInfo = AV.Object.extend('Activity');
var ActivityShare = AV.Object.extend('ActivityShare');
var ActivityShareList = AV.Object.extend('ActivityShareList');
var orderController = require('../app_module/diy/controllers/order');
module.exports = {
    //营运大转盘抽奖
    turntableActivity:function(uid,level,activityName,openid,nickname,image,shareid,remark){
        var promise = new AV.Promise();
        var finalRule = {};
        async.auto({
            //获取activity表中的大转盘配置信息
            getTurntableInfo:function(callback){
                activityService.getTurntableInfo().then(function(data){
                    if(data){
                        callback(null, data.get('info'));
                    }else{
                        callback({code:-1,msg:'当前没有活动'});
                    }
                });
            },
            getCountByToday:function(callback){
                activityService.getAllTimesByDay(uid).then(function(data){
                    callback(null, data);
                });
            },
            //分析数据
            makeTurntableInfo:['getTurntableInfo',function(callback,results){
                if(results.getTurntableInfo[activityName]){
                    callback(null, results.getTurntableInfo[activityName]);
                }else{
                    callback({code:-1,msg:'数据库中没有符合条件的活动'});
                }
            }],
            //分别执行赠送礼品，根据rule规则，赠送积分、赠送优惠券、赠送现金、赠送水果
            //首先判断time、cutPoint 和 cutPointLevel
            getRules:["makeTurntableInfo","getCountByToday",function(callback,results){
                var finalRules = {updateResult:-1,cutPoint:-1,eachTime:-1,ladderTime:-1}
                if(results.makeTurntableInfo ){
                    var rules = results.makeTurntableInfo;
                    var countToday = results.getCountByToday ;
                    //判断次数，并从activityResult中获取当天累计抽奖次数count，如果count>=time,则不可以抽奖
                    if(rules.time === -2){
                        //获取ActivityResults中的restTime字段
                        //判断是否可以继续抽奖
                        if(parseInt(countToday.restTime) - parseInt(countToday.time) > 0){
                            //可以抽奖，并显示次数
                            finalRules['updateResult'] = rules.time ;
                        }else{
                            //提示已达上限
                            return callback({code:-2,msg:"已达上限，邀请好友一起来抽奖吧"})
                        }
                    }else{
                        if(rules.time != -1 && countToday.oneDay >= rules.time){
                            //直接退出全部程序
                            return callback({code:-2,msg:"已达上限，明天再来抽奖吧"})
                        }else{
                            //执行正常流程
                            finalRules['updateResult'] = rules.time ;
                        }
                    }
                    if(rules.cutPoint === -1){
                        //不扣减积分
                        finalRules['cutPoint'] = -1 ;
                    }else{
                        finalRules['cutPoint'] = 0 ;
                        if(rules.cutPointLevel.eachTime != -1 && rules.cutPointLevel.ladderTime === -1){
                            //每次扣减相同积分
                            finalRules['eachTime'] = rules.cutPointLevel.eachTime;
                        }else{
                            //每次扣减ladderTime+ladderTime*time个积分
                            finalRules['ladderTime'] = rules.cutPointLevel.ladderTime;
                        }
                    }
                }
                callback(null, finalRules) ;
            }],
            //扣减积分
            cutPoint:['getRules',function(callback,results){
                var finalRules = results.getRules ;
                if(finalRules){
                    if(finalRules.cutPoint!=-1){
                        //扣减积分
                        var cutPoint = 0;
                        if(finalRules.eachTime != -1){
                            cutPoint = finalRules.eachTime ;
                        }else{
                            cutPoint = finalRules.ladderTime + finalRules.ladderTime * results.getCountByToday ;
                        }
                        activityService.cutPoint(uid,cutPoint).then(function(data){
                            if(data.code === 0){
                                callback(null, {code:1,msg:'积分扣减成功'});
                            }else{
                                callback(null,{code:-3,msg:'积分扣减失败1'});
                            }
                        }).catch(function(err){
                            callback(null, {code:-4,msg:'积分扣减失败'});
                        });
                    }else{
                        callback(null,{code:0,msg:'无需扣减积分1'+finalRules.cutPoint});
                    }
                }else{
                    callback(null,{code:0,msg:'无需扣减积分2'});
                }
            }],
            updateResultFlow:['getRules','cutPoint',function(callback,results){
                if(results.cutPoint.code===-3){
                    return callback({code:-3,msg:'积分不足，不能抽奖'})
                }
                if(results.cutPoint.code===-4){
                    return callback({code:-4,msg:'扣减积分失败，请重新抽奖'})
                }
                var finalRules = results.getRules ;
                if(finalRules){
                    activityService.insertTimeToResult(uid,level,activityName,finalRules.updateResult).then(function(data){
                        callback(null, {code:0,msg:'插入成功'})
                    }).catch(function(err){
                        callback(null, {code:-1})
                    });

                }else{
                    callback(null,{code:-1,msg:'无需插入'});
                }
            }],
            //向ActivityShareList表中插入数据
            updateShareList:['updateResultFlow',function(callback,results){
                if(shareid){
                    activityService.createShareList(openid,nickname,image,shareid,remark).then(function(data){
                        if(data){
                            callback(null, {code:0});
                        }else{
                            callback(null, {code:1});
                        }
                    }).catch(function(){
                        callback(null, {code:-1});
                    });
                }else{
                    callback(null, {code:1});
                }

            }],
            giveRewards:["updateResultFlow",'updateShareList',function(callback,results){
                var rules = results.makeTurntableInfo ;
                var rewards = rules.rewards ;
                var reward = rewards[level] ;
                switch (reward.type){
                    case 0 :
                        //没有中奖
                        callback(null, {code:0,msg:'没有中奖'});
                        break;
                    case 1 :
                        //发放积分
                        activityService.givePoint(uid,reward.reward).then(function(data){
                            if(data.code === 0){
                                callback(null, {code:1,msg:'积分发放成功'});
                            }else{
                                callback(null, {code:-1,msg:'积分发放失败'});
                            }
                        }).catch(function(){
                            callback(null, {code:-1,msg:'积分发放失败'});
                        });
                        break;
                    case 2 :
                        activityService.giveCoupons(uid,reward.reward).then(function(data){
                            if(data.code === 0){
                                callback(null, {code:2,msg:'优惠券发放成功'});
                            }else{
                                callback(null, {code:-2,msg:'优惠券发放失败'});
                            }
                        }).catch(function(){
                            callback(null, {code:-2,msg:'优惠券发放失败'});
                        });
                        break;
                    case 3 :
                        activityService.giveCash(uid,reward.reward).then(function(data){
                            if(data.code === 0){
                                callback(null, {code:3,msg:'现金发放成功'});
                            }else{
                                callback(null, {code:-3,msg:'现金发放失败'});
                            }
                        }).catch(function(){
                            callback(null, {code:-3,msg:'现金发放失败'});
                        });
                        break;
                    case 4 :
                        activityService.giveGiftToCart(uid,reward.reward.pid,reward.reward.psid).then(function(data){
                            if(data.code === 0){
                                callback(null, {code:4,msg:'水果发放成功'});
                            }else{
                                callback(null, {code:-4,msg:'水果发放失败'});
                            }
                        }).catch(function(){
                            callback(null, {code:-4,msg:'水果发放失败'});
                        });
                        break;
                    case 5 :        //发放自提商品
                        orderController.diyaddOrder(uid,reward.reward.pid).then(function(data){
                            if(data.code === 0){
                                callback(null, {code:5,msg:'自提奖品发放成功'});
                            }else{
                                callback(null, {code:-5,msg:'自提奖品发放失败'});
                            }
                        }).catch(function(){
                            callback(null, {code:-5,msg:'自提奖品发放失败'});
                        });
                        break;
                    default :
                        break;
                }
            }],
            finalFun:['giveRewards',function(callback,results){
                var finalFunResult = {code:-9999,msg:'网络出问题了，请联系客服咨询'}
                switch (results.giveRewards.code){
                    case 0:
                        //未中奖
                        finalFunResult["code"] = 0;
                        finalFunResult["msg"] = "sorry，您没有中奖，继续努力哦!";
                        break;
                    case 1:
                        //送积分
                        finalFunResult["code"] = 1;
                        finalFunResult["msg"] = "恭喜您获取积分奖励，请至个人中心查收!";
                        break;
                    case -1:
                        //送积分失败
                        finalFunResult["code"] = -1;
                        finalFunResult["msg"] = "恭喜您获取积分奖励，但是小果没能给您成功发放，请联系客服小姐姐帮忙吧!";
                        break;
                    case 2:
                        //优惠券
                        finalFunResult["code"] = 2;
                        finalFunResult["msg"] = "恭喜您获取优惠券奖励，请前往个人中心查收!";
                        break;
                    case -2:
                        //未中奖
                        finalFunResult["code"] = -2;
                        finalFunResult["msg"] = "恭喜您获取优惠券奖励，但是小果没能给您成功发放，请联系客服小姐姐帮忙吧!";
                        break;

                    case 3:
                        //未中奖
                        finalFunResult["code"] = 3;
                        finalFunResult["msg"] = "恭喜您获取现金奖励，请至个人中心查收!";
                        break;
                    case -3:
                        //未中奖
                        finalFunResult["code"] = -3;
                        finalFunResult["msg"] = "恭喜您获取现金奖励，但是小果没能给您成功发放，请联系客服小姐姐帮忙吧!";
                        break;
                    case 4:
                        //未中奖
                        finalFunResult["code"] = 4;
                        finalFunResult["msg"] = "恭喜您获取水果礼品奖励，请前往购物车查收!";
                        break;
                    case -4:
                        //未中奖
                        finalFunResult["code"] = -4;
                        finalFunResult["msg"] = "恭喜您获取水果礼品奖励，但是小果没能给您成功发放，请联系客服小姐姐帮忙吧!";
                        break;
                    case 5:
                        //未中奖
                        finalFunResult["code"] = 5;
                        finalFunResult["msg"] = "恭喜您获取换购果汁的机会（苹果汁、香梨汁二选一），请移驾到‘个人中心’的‘我的自提’中查看。";
                        break;
                    case -5:
                        //未中奖
                        finalFunResult["code"] = -5;
                        finalFunResult["msg"] = "恭喜您获取自提商品奖励，但是小果没能给您成功发放，请联系客服小姐姐帮忙吧!";
                        break;
                    default :
                        break;
                }
                callback(null, finalFunResult);
            }]
        },function(err,results){
            if(err){
                var errResult = {code:-9999,msg:'啊哦，出错了，您可以刷新下然后继续抽奖!'}
                switch (err.code){
                    case -1:
                        //当前没有活动
                        errResult["code"] = -1;
                        errResult["msg"] = "sorry,当前活动还没开启哦，如有疑问，可联系客服小姐姐!";
                        break;
                    case -2:
                        //已达活动次数上线
                        errResult["code"] = -2;
                        errResult["msg"] = "sorry,您当天抽奖次数已达系统上限，请明天再来抽奖，如有疑问，可联系客服小姐姐!";
                        break;
                    case -3:
                        errResult["code"] = -3;
                        errResult["msg"] = "sorry,您的积分不足或者网络出了问题，请您再试一次，如有疑问，可联系客服小姐姐!";
                        //积分不足
                        break;
                    case -4:
                        //扣减积分失败，可以继续抽奖
                        errResult["code"] = -4;
                        errResult["msg"] = "sorry,您的积分不足，不能参与抽奖，如有疑问，可联系客服小姐姐!";
                        break;
                    default :
                        //真的出错了
                        break;
                }
                promise.reject(errResult);
            }else{
                //promise.resolve(results.getTurntableInfo[activityName]);
                promise.resolve(results.finalFun);
            }
        });
        return promise;
    },

    //判断是否需要创建
    /**
     * 创建新的符合条件的分享数据
     * @param openid
     * @param nickname
     * @param image
     * @returns {*|promise}
     */
    createNewShare:function(openid,nickname,image){
        var promise = new AV.Promise();
        async.auto({
            getCount:function(callback){
                activityService.countActivityShareByOpenid(openid).then(function(data){
                    if(data <= 10){  //分享最大次数
                        //允许创建
                        callback(null, {code:0,msg:'允许创建一条分享'});
                    }else{
                        callback(null,{code:-1,msg:'分享上限，不允许创建'});
                    }
                }).catch(function(){
                    return callback({code:-2,msg:'网络异常'});
                });
            },
            queryRewards:function(callback){
                /*activityService.queryReward().then(function(data){
                    callback(null, data);
                }).catch(function(err){
                    callback({code:-2});
                });*/
                callback(null, {});
            },
            queryShareList:function(callback){
                activityService.queryShareList().then(function(data){
                    callback(null, data);
                }).catch(function(){
                    callback({code:-2});
                });
            },
            createShare:['getCount','queryRewards','queryShareList',function(callback,results){
                if(results.getCount.code === 0){
                    activityService.createShare(openid,nickname,image).then(function(data){
                        if(data){
                            callback(null, {code:0,msg:'创建成功',data:data,rewards:results.queryRewards,shareList:results.queryShareList});
                        }else{
                            callback(null, {code:1,msg:'创建失败了，需要重新创建',data:data,rewards:results.queryRewards,shareList:results.queryShareList});
                        }
                    });
                }else{
                    activityService.queryShareFirst(openid).then(function(data){
                        if(data){
                            //达到分享上线，展示默认活动首页
                            callback(null, {code:-1,msg:'分享上限，不允许创建',data:data,rewards:results.queryRewards,shareList:results.queryShareList});
                        }else{
                            return callback({code:-2,msg:'没有获取到分享数据'});
                        }
                    }).catch(function(err){
                        return callback({code:-2,msg:'没有获取到分享数据'});
                    });
                }
            }]
        },function(err,results){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(results.createShare);
            }
        });
        return promise;
    },

    /**
     * 根据用户openid和shareid判断用户是否抽过奖
     * @param openid
     * @param shareid
     * @returns {*|promise}
     */
    isTurntabledInShare:function(openid,shareid){
        var promise = new AV.Promise();
        async.waterfall([
            function(callback){
                activityService.isTurntabledInShare(openid,shareid).then(function(data){
                    if(!data || data.length <1){
                        //不存在
                        callback(null,{code:0});
                    }else{
                        //存在，不能进行抽奖
                        callback({code:-1,msg:'您已抽过一次，传递给好友继续抽奖'});
                    }
                }).catch(function(err){
                    callback({code:-2,msg:'抱歉，出错了'});
                });
            },
            function(data,callback){
                if(data.code === 0){
                    activityService.queryActivityShare(shareid).then(function(share){
                        if(share.code === 0){
                            //查找成功，返回创始人的openid
                            callback(null, {code:0,createOpenid:share.data.id});
                        }else{
                            callback(null, {code:-1});
                        }
                    }).catch(function(err){
                        callback(null,{code:-1});
                    });
                }
            },
            function(data,callback){
                if(data.code === 0){
                    if(data.createOpenid === "oEQYPtxwE9CKFScl0fROZ-Jeuqr0"){
                        callback(null,{code:0});
                    }else{
                        activityService.countShareListByShareid(shareid).then(function(data){
                            if(data >= 10){
                                //不能再抽奖
                                if(openid === "oEQYPtxwE9CKFScl0fROZ-Jeuqr0"){
                                    callback(null,{code:0});
                                }else{
                                    callback({code:-1,msg:'最多只能有10名好友抽奖哦'});
                                }
                            }else{
                                callback(null,{code:0});
                            }
                        });
                    }
                }else{
                    callback({code:-2,msg:'抱歉，出错了'});
                }
            }
        ],function(err,results){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(results);
            }
        });
        return promise;
    },
    createShareList:function(openid,shareid,nickname,img,remark){

    },

    /**
     * 根据shareid获取share表和sharelist表中的数据
     * @param shareid
     * @returns {*|promise}
     */
    queryShare:function(shareid){
        //根据shareid获取全部中奖信息
        var promise = new AV.Promise();
        async.auto({
            share:function(callback){
                //从share表中获取
                activityService.queryActivityShare(shareid).then(function(data){
                    callback(null, data.data);
                }).catch(function(err){
                    callback(err);
                });
            },
            shareList:function(callback){
                activityService.queryShareList(shareid).then(function(data){
                    callback(null, data);
                }).catch(function(){
                    callback({code:-2});
                });
            },
            queryRewards:function(callback){
                /*activityService.queryReward().then(function(data){
                    callback(null, data);
                }).catch(function(err){
                    callback({code:-2});
                });*/
                callback(null, {});
            },
            final:['share','shareList','queryRewards',function(callback,results){
                callback(null, {share:results.share,shareList:results.shareList,rewards:results.queryRewards});
            }]
        },function(err,results){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(results.final);
            }
        });
        return promise ;
    },
    countReward:function(){
        var promise = new AV.Promise();
        async.auto({
            query1:function(callback){
                activityService.countReward('免费果汁').then(function(count){
                    callback(null, count);
                }).catch(function(err){
                    callback(null, 180);
                });
            },
            query2:function(callback){
                activityService.countReward('3元果汁').then(function(count){
                    callback(null, count);
                }).catch(function(err){
                    callback(null, 4406);
                });
            },
            query3:function(callback){
                activityService.countReward('5元果汁').then(function(count){
                    callback(null, count);
                }).catch(function(err){
                    callback(null, 6014);
                });
            },
            query4:function(callback){
                activityService.countReward('满100减10元').then(function(count){
                    callback(null, count);
                }).catch(function(err){
                    callback(null, 3349);
                });
            },
            query5:function(callback){
                activityService.countReward('满30减3元').then(function(count){
                    callback(null, count);
                }).catch(function(err){
                    callback(null, 3349);
                });
            },
            query6:function(callback){
               //iPhone6s
                callback(null, 0);
            },
            //iPad mini
            query7:function(callback){
                //iPhone6s
                callback(null, 0);
            },
            //iPod
            query8:function(callback){
                //iPhone6s
                callback(null, 0);
            },
            final:['query1','query2','query3','query4','query5','query6','query7','query8',function(callback,results){
                callback(null, {fruit0:results.query1,fruit3:results.query2,fruit5:results.query3,coupon10:results.query4,coupon3:results.query5,
                    iphone:results.query6,ipad:results.query7,ipod:results.query8
                });
            }],
            /*saveReward:['final',function(callback,results){
                activityService.saveReward(results.final).then(function(data){
                    callback(null, {code:0});
                }).catch(function(err){
                    callback(null, {code:-1});
                });
            }]*/
        },function(err,results){
            if(err){
                promise.reject(results.final);
            }else{
                promise.resolve(results.final);
            }
        });
        return promise;
    },
    countRewardNew:function(){
        var promise = new AV.Promise();
        async.auto({
            query1:function(callback){
                var query = new AV.Query(ActivityShareList);
                query.containedIn('remark',['免费果汁','3元果汁','5元果汁']);
                query.count().then(function(count){
                    callback(null, count);
                })
            },
            query2:function(callback){
                activityService.countReward('满100减10元').then(function(count){
                    callback(null, count);
                }).catch(function(err){
                    callback(null, 3349);
                });
            },
            query3:function(callback){
                //iPhone6s
                callback(null, 0);
            },
            //iPad mini
            query4:function(callback){
                //iPhone6s
                callback(null, 0);
            },
            //iPod
            query5:function(callback){
                //iPhone6s
                callback(null, 0);
            },
            final:['query1','query2','query3','query4','query5' ,function(callback,results){
                callback(null, {fruit:results.query1,coupon10:results.query2,iphone:results.query3,ipad:results.query4,ipod:results.query5});
            }]
        },function(err,results){
            if(err){
                promise.reject(results.final);
            }else{
                promise.resolve(results.final);
            }
        });
        return promise;
    },
};
